package com.itheima.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.exception.BusinessException;
import com.itheima.mapper.ClazzMapper;
import com.itheima.mapper.StudentMapper;
import com.itheima.pojo.entity.Clazz;
import com.itheima.pojo.entity.PageResult;
import com.itheima.pojo.query.ClazzQueryParam;
import com.itheima.service.ClazzService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PathVariable;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @author zzw
 * @date 2025/4/23
 * @description 班级服务实现类
 */
@Service
public class ClazzServiceImpl implements ClazzService {

    @Autowired
    private ClazzMapper clazzMapper;

    @Autowired
    private StudentMapper studentMapper;

    /**
     * 分页查询班级
     *
     * @param clazzQueryParam 查询参数
     * @return PageResult<Clazz> 分页结果
     */
    @Override
    public PageResult<Clazz> page(ClazzQueryParam clazzQueryParam) {
        //1. 设置PageHelper分页参数
        PageHelper.startPage(clazzQueryParam.getPage(), clazzQueryParam.getPageSize());

        //2. 执行查询
        Page<Clazz> clazzList = clazzMapper.page(clazzQueryParam);

        //3. 封装分页结果
        return new PageResult<>(clazzList.getTotal(), clazzList.getResult());

    }

    /**
     * 查询所有班级
     *
     * @return List<Clazz> 班级列表
     */
    @Override
    public List<Clazz> list() {
        return clazzMapper.list();
    }

    /**
     * 根据id查询班级
     *
     * @param id 班级id
     * @return Result 封装结果
     */
    @Override
    public Clazz getById(@PathVariable Integer id) {
        return clazzMapper.getById(id);
    }

    /**
     * 根据id删除班级
     *
     * @param id 班级id
     */
    @Override
    public void delete(Integer id) {
        // 1.检查当前班级下是否有学员
        if (studentMapper.countByClazzId(id) > 0) {
            // 2.如果班级下有学员，抛出业务异常
            throw new BusinessException("当前班级下有学员，不能删除");
        }

        // 3.如果班级下没有学员，执行删除操作
        clazzMapper.delete(id);
    }

    /**
     * 添加班级
     *
     * @param clazz 班级
     */
    @Override
    public void save(Clazz clazz) {
        clazz.setCreateTime(LocalDateTime.now());
        clazz.setUpdateTime(LocalDateTime.now());
        clazzMapper.save(clazz);
    }

    /**
     * 修改班级
     *
     * @param clazz 班级
     */
    @Override
    public void update(Clazz clazz) {
        clazz.setUpdateTime(LocalDateTime.now());
        clazzMapper.update(clazz);
    }
}
